<template>
  <PageContainer title="修改密码">
    <el-row>
      <el-col :span="12">
        <el-form
          :model="pwdForm"
          :rules="rules"
          ref="pwdFormRef"
          label-width="120px"
        >
          <el-form-item label="原密码" prop="old_pwd">
            <el-input v-model="pwdForm.old_pwd" type="password" />
          </el-form-item>
          <el-form-item label="新密码" prop="new_pwd">
            <el-input v-model="pwdForm.new_pwd" type="password" />
          </el-form-item>
          <el-form-item label="确认密码" prop="re_pwd">
            <el-input v-model="pwdForm.re_pwd" type="password" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">修改密码</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </PageContainer>
</template>
<script lang="ts" setup name="">
import { ref, reactive } from 'vue'
import PageContainer from '@/components/PageContainer.vue'
import { updatePwdService } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const pwdFormRef = ref()

const userStore = useUserStore()

const router = useRouter()

const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

const validateNewPwd = (rule: any, value: any, callback: any) => {
  if (value === pwdForm.value.old_pwd) {
    callback(new Error('原密码和新密码不能一致'))
  } else {
    callback()
  }
}

const validateRePwd = (rule: any, value: any, callback: any) => {
  if (value !== pwdForm.value.new_pwd) {
    callback(new Error('新密码和确认密码不一致'))
  } else {
    callback()
  }
}

const rules = reactive({
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '原密码长度应为6-15位', trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '新密码长度应为6-15位', trigger: 'blur' },
    { validator: validateNewPwd, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '确认密码长度应为6-15位', trigger: 'blur' },
    { validator: validateRePwd, trigger: 'blur' }
  ]
})

const handleSubmit = async () => {
  //校验
  await pwdFormRef.value.validate()
  const res = await updatePwdService(pwdForm.value)
  // console.log(res)
  ElMessage.success(res.data.message)
  //修改成功后 退出重新登录  清除个人信息
  userStore.setUser({})
  userStore.setToken('')
  router.push('/login')
}

const handleReset = () => {
  pwdFormRef.value.resetFields()
}
</script>
<style scoped></style>
